/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.dusin.teachassist.servlet.student;

import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileExistsException;
import org.apache.log4j.Logger;
import org.dusin.teachassist.util.WordUtil;
import org.dusin.teachassistdbservice.serviceimpl.GeneralService;
import org.dusin.teachassistdbservice.util.TheUtil;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author dusin
 */
@WebServlet(name = "UploadReport", urlPatterns = {"/servlet/student/UploadReport"})
public class UploadReport extends HttpServlet {

    private GeneralService instance;
    static Logger logger = Logger.getLogger(GeneralService.class);
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/json;charset=UTF-8");
        HttpSession session = request.getSession();
        //JSONArray json = new JSONArray();     //响应数据为数组，为后面一次上传多个文件做准备
        Gson gson = new Gson();
        Map<String,Object> resultMap = new HashMap<>();
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
        }

        ServletContext servletConfig = request.getServletContext();
        String dataDirectoryStr = servletConfig.getInitParameter("DataDirectory");
        if (dataDirectoryStr == null) {
            dataDirectoryStr = "e:/ta";
        }
        //double threshhold = Double.parseDouble(servletConfig.getInitParameter("threshhold"));

        Integer teachclassid = (Integer) session.getAttribute("teachclassid");
        String type = "1";    // 2-上传作业，1-默认，上传实验
        String jobId = null;
        String teacherNo = (String) session.getAttribute("teacherNo");
        String semester = TheUtil.getCurrentSemester();
        String courseName = (String) session.getAttribute("courseName");
        String no = "1";
        double threshold = 85;
        String studentNo = (String) session.getAttribute("studentNo");
        String studentName = (String) session.getAttribute("studentName");
        String fileUploadPath = dataDirectoryStr + "/" + teacherNo + "/" + semester + "/" + courseName + "/实验/";
        String savedFileName = studentNo + "-" + studentName + "-";

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        //System.out.println("repository:" + repository.getAbsolutePath());
        factory.setRepository(repository);
        ServletFileUpload uploadHandler = new ServletFileUpload(factory);
        uploadHandler.setHeaderEncoding("utf-8");  //可以解决中文文件名乱码问题
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        instance = (GeneralService) context.getBean("generalService");
        //上传之前要先确认是否已经截止上传，待实现。目前在前端控制，后端控制更安全
        try {
            FileItem uploadFileItem = null;
            List<FileItem> items = uploadHandler.parseRequest(request);
            for (FileItem item : items) {

                if (!item.isFormField()) {
                    uploadFileItem = item;

                } else {
                    if ("jobId".equals(item.getFieldName())) {
                        jobId = item.getString();
                    } else if ("no".equals(item.getFieldName())) {
                        no = item.getString();
                    } else if ("type".equals(item.getFieldName())) {
                        type = item.getString();
                        if ("2".equals(type)) {
                            fileUploadPath = dataDirectoryStr + "/" + teacherNo + "/" + semester + "/" + courseName + "/作业/";
                        }
                    } else if ("threshold".equals(item.getFieldName())) {
                        String strThreshold = item.getString();
                        try {
                            threshold = Double.parseDouble(strThreshold);
                        } catch (Exception e) {
                            threshold = 85;
                        }
                    }
                }
            }
            
            String docType = TheUtil.fileSuffix(uploadFileItem.getName());
            String filename = savedFileName + no + "." + TheUtil.fileSuffix(uploadFileItem.getName());
            Path dataPath = Paths.get(fileUploadPath + no + "/");
            if (Files.notExists(dataPath)) {  //目录不存在，则创建
                Files.createDirectories(dataPath);
            }
            File file = new File(fileUploadPath + no, filename);
            if(file.exists()){//如果文件已存在，则先删除                
                file.delete();
                logger.info("文件已存在，文件被删除"+filename);
            }
            //检查文档相似度
            Map<String, Object> map = null;
            double maxDegree = 0;
            if ("1".equals(type)) {  //实验报告检查相似度
                map = WordUtil.checkSimilarity(uploadFileItem.getInputStream(), filename,docType, fileUploadPath + no);
                maxDegree = (Double)map.get("degree");
            }
            if (maxDegree < threshold / 100.0) {
                uploadFileItem.write(file);
                if ("2".equals(type)) {
                    instance.trUpdateHomework(Integer.parseInt(jobId), studentNo, filename);
                } else {//实验
                    double degree = (Double) map.get("degree");
                    String degreeFilename = (String) map.get("filename");
                    //instance.trUpdateScore(Integer.parseInt(jobId), studentNo, 0, 1, "重复率:"+degree+" 重复文件:"+degreeFilename, filename, degree, degreeFilename);
                    instance.trUpdateScore(Integer.parseInt(jobId), studentNo, 0, 1, "", filename, degree, degreeFilename);
                }
                resultMap.put("name", uploadFileItem.getName());                
                resultMap.put("status", true);
                resultMap.put("msg", "上传成功,最高重复率:" + maxDegree);
                
            } else {
                if ("1".endsWith(type)) {
                    double degree = (Double) map.get("degree");
                    degree = Math.round(degree*1000)/1000.0;
                    String degreeFilename = (String) map.get("filename");
                    instance.trUpdateScore(Integer.parseInt(jobId), studentNo, -1, 0, "重复率:"+degree+" 重复文件:"+degreeFilename, filename, degree, degreeFilename);
                }
                resultMap.put("name", uploadFileItem.getName());
                resultMap.put("status", false);
                maxDegree = Math.round(maxDegree*1000)/1000.0;
                resultMap.put("msg", "上传失败,与已上传作业重复率高,阈值：" + threshold / 100.0 + "实际值：" + maxDegree);
                
            }

        } catch (FileExistsException e) {
            
                resultMap.put("status", false);
                resultMap.put("msg", "目标文件已存在");
            
                e.printStackTrace();
        } catch (Throwable t) {
            
                resultMap.put("status", false);
                resultMap.put("msg", t.getMessage());
                t.printStackTrace();
        } finally {
            out.println(gson.toJson(resultMap));
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
